package com.liuwei.spring.cloud.common.utils;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * @author : PdfHelper
 * @version V1.0
 * @date: 2023/9/5 1:56 下午
 * @Description: TODO
 */
public class PdfHelper {

    public static final float DEFAULT_DPI = 150;
    public static final String DEFAULT_IMAGE_FORMAT = ".png";

    /**
     * 将 PDF 转换为默认的 PNG 格式
     * @param input
     * @param output
     * @param pageSize 期望转换图片的页数
     * @return PDF 总页数
     * @throws IOException
     */
    public static int convertToImage(InputStream input, OutputStream output,int pageSize) throws IOException {
        PDDocument pdDocument = PDDocument.load(input);
        PDFRenderer pdfRenderer = new PDFRenderer(pdDocument);

        int pages = pdDocument.getNumberOfPages();
        int len = Math.min(pages, pageSize);
        int width;

        int shiftHeight = 0;
        int[] singleImgRGB;

        BufferedImage imageResult;
        for (int i = 0; i < len; i++) {
            BufferedImage image = pdfRenderer.renderImageWithDPI(i, DEFAULT_DPI, ImageType.RGB);
            width = image.getWidth();
            int imageHeight = image.getHeight();
            imageResult = new BufferedImage(width, imageHeight, BufferedImage.TYPE_INT_RGB);
            singleImgRGB = image.getRGB(0, 0, width, imageHeight, null, 0, width);
            imageResult.setRGB(0, shiftHeight, width, imageHeight, singleImgRGB, 0, width);
            ImageIO.write(imageResult, DEFAULT_IMAGE_FORMAT.replace(".", ""), output);
        }
        pdDocument.close();
        return pages;
    }

    /**
     *  将 PDF 转换为默认的 PNG 格式
     * @param pdfFile
     * @param imageFile
     * @param pageSize PDF 总页数
     * @return
     * @throws Exception
     */
    public static int convertToImage(File pdfFile, File imageFile, int pageSize) throws Exception {
        if (pdfFile == null) {
            throw new IllegalArgumentException("PdfFile == null!");
        }
        if (imageFile == null) {
            throw new IllegalArgumentException("ImageFile == null!");
        }
        try(InputStream input = new FileInputStream(pdfFile);
            FileOutputStream output = new FileOutputStream(imageFile);
        ){
            return convertToImage(input,output,pageSize);
        }
    }
}
